<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Support\Facades\Cache;

class SystemSetting extends Model
{
    protected $fillable = [
        'key',
        'value',
        'type',
        'group',
        'label',
        'description',
        'options',
        'is_public',
        'is_required',
        'sort_order'
    ];

    protected $casts = [
        'is_public' => 'boolean',
        'is_required' => 'boolean',
        'options' => 'array',
        'sort_order' => 'integer'
    ];

    /**
     * 获取设置值的访问器
     */
    protected function value(): Attribute
    {
        return Attribute::make(
            get: function ($value) {
                return match ($this->type) {
                    'boolean' => (bool) $value,
                    'integer' => (int) $value,
                    'json' => json_decode($value, true),
                    default => $value,
                };
            },
            set: function ($value) {
                return match ($this->type) {
                    'boolean' => $value ? '1' : '0',
                    'integer' => (string) $value,
                    'json' => json_encode($value),
                    default => $value,
                };
            }
        );
    }

    /**
     * 获取设置值（静态方法）
     */
    public static function get(string $key, $default = null)
    {
        $cacheKey = "system_setting_{$key}";
        
        return Cache::remember($cacheKey, 3600, function () use ($key, $default) {
            $setting = static::where('key', $key)->first();
            return $setting ? $setting->value : $default;
        });
    }

    /**
     * 设置值（静态方法）
     */
    public static function set(string $key, $value, array $attributes = []): bool
    {
        $setting = static::updateOrCreate(
            ['key' => $key],
            array_merge($attributes, ['value' => $value])
        );

        // 清除缓存
        Cache::forget("system_setting_{$key}");
        
        return $setting->wasRecentlyCreated || $setting->wasChanged();
    }

    /**
     * 获取分组设置
     */
    public static function getByGroup(string $group): \Illuminate\Database\Eloquent\Collection
    {
        return static::where('group', $group)
            ->orderBy('sort_order')
            ->orderBy('label')
            ->get();
    }

    /**
     * 获取公开设置（前端可访问）
     */
    public static function getPublicSettings(): array
    {
        $cacheKey = 'system_settings_public';
        
        return Cache::remember($cacheKey, 3600, function () {
            return static::where('is_public', true)
                ->pluck('value', 'key')
                ->toArray();
        });
    }

    /**
     * 清除所有设置缓存
     */
    public static function clearCache(): void
    {
        Cache::flush();
    }

    /**
     * 清除所有缓存
     */
    public static function clearAllCache()
    {
        Cache::flush();
        // 清除配置缓存
        if (function_exists('config_clear')) {
            config_clear();
        }
    }



    /**
     * 获取所有设置的键值对
     */
    public static function getAllSettings()
    {
        return Cache::remember('system_settings_all', 3600, function () {
            $settings = self::all();
            $result = [];
            foreach ($settings as $setting) {
                $result[$setting->key] = $setting->value;
            }
            return $result;
        });
    }

    /**
     * 批量设置多个配置
     */
    public static function setMultiple(array $settings)
    {
        foreach ($settings as $key => $value) {
            self::set($key, $value);
        }
        
        // 清除相关缓存
        Cache::forget('system_settings_public');
        Cache::forget('system_settings_all');
        
        // 触发配置重新加载
        self::reloadConfigs();
    }

    /**
     * 重新加载配置到Laravel配置系统
     */
    public static function reloadConfigs()
    {
        try {
            $settings = self::all();
            
            foreach ($settings as $setting) {
                // 同步到config
                \Config::set("system.{$setting->key}", $setting->value);
                
                // 同步特殊配置
                switch ($setting->key) {
                    case 'app_name':
                        \Config::set('app.name', $setting->value);
                        break;
                    case 'app_url':
                        \Config::set('app.url', $setting->value);
                        break;
                    // 可以根据需要添加更多特殊配置
                }
            }
        } catch (\Exception $e) {
            \Log::error('Failed to reload system settings: ' . $e->getMessage());
        }
    }

    /**
     * 模型事件
     */
    protected static function booted()
    {
        static::saved(function ($setting) {
            // 清除单个设置缓存
            $cacheKey = "system_setting_{$setting->key}";
            Cache::forget($cacheKey);
            
            // 清除批量缓存
            Cache::forget('system_settings_public');
            Cache::forget('system_settings_all');
            
            // 重新加载配置
            self::reloadConfigs();
        });

        static::deleted(function ($setting) {
            // 清除单个设置缓存
            $cacheKey = "system_setting_{$setting->key}";
            Cache::forget($cacheKey);
            
            // 清除批量缓存
            Cache::forget('system_settings_public');
            Cache::forget('system_settings_all');
            
            // 重新加载配置
            self::reloadConfigs();
        });
    }
}
